import React, { useEffect, useState } from "react";
 
export default (): JSX.Element => {
  const [w, setW] = useState<Worker>()
  const [num, setNum] = useState(1)
  const startWorker = () => {
    setW(new Worker("http://localhost:3322/front/worker.js"))
  }
  function stopWorker() {
    if (!w) return 
    w.terminate(); // 终止进程运行，下回启动重头开始
  }
  useEffect(() => {
    if (!w || !!w.onmessage) return 
    w.onmessage = function (event) {
      // 通过postMessage和onMessage进行线程之间的通信
      console.log("通知来了", event);
      setNum(event.data)
    };
    w.postMessage(34234234) // 发送信息
  }, [w])
  return <div>
    web-worker
    {num}
    <button onClick={startWorker}>开始</button>
    <button onClick={stopWorker}>结束</button>
  </div>;
};